from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from products.models import Category, Product
from orders.models import Order, OrderItem
from delivery.models import Delivery
from django.utils import timezone
import random

User = get_user_model()

class Command(BaseCommand):
    help = '生成测试数据'

    def handle(self, *args, **kwargs):
        self.stdout.write('开始生成测试数据...')

        # 创建测试用户
        self.create_test_users()
        
        # 创建商品分类
        self.create_categories()
        
        # 创建商品
        self.create_products()
        
        # 创建订单
        self.create_orders()
        
        # 创建配送任务
        self.create_deliveries()

        self.stdout.write(self.style.SUCCESS('测试数据生成完成！'))

    def create_test_users(self):
        # 创建管理员
        if not User.objects.filter(username='admin').exists():
            admin = User.objects.create_user(
                username='admin',
                password='admin123',
                role='admin'
            )
        
        # 创建采购员
        if not User.objects.filter(username='purchaser').exists():
            purchaser = User.objects.create_user(
                username='purchaser',
                password='purchaser123',
                role='purchaser'
            )
        
        # 创建销售员
        if not User.objects.filter(username='salesman').exists():
            salesman = User.objects.create_user(
                username='salesman',
                password='salesman123',
                role='salesman'
            )
        
        # 创建配送员
        if not User.objects.filter(username='deliveryman').exists():
            deliveryman = User.objects.create_user(
                username='deliveryman',
                password='deliveryman123',
                role='deliveryman'
            )
        
        # 创建客户
        if not User.objects.filter(username='customer').exists():
            customer = User.objects.create_user(
                username='customer',
                password='customer123',
                role='customer'
            )

        self.stdout.write('测试用户创建完成')

    def create_categories(self):
        categories = [
            '蔬菜', '水果', '肉类', '海鲜', '禽蛋', '粮油', '调味品'
        ]
        
        for name in categories:
            Category.objects.get_or_create(name=name)
        
        self.stdout.write('商品分类创建完成')

    def create_products(self):
        categories = Category.objects.all()
        
        products_data = [
            ('有机生菜', '蔬菜', 5.8, 100),
            ('红富士苹果', '水果', 12.8, 200),
            ('猪里脊', '肉类', 35.8, 50),
            ('基围虾', '海鲜', 68.8, 30),
            ('土鸡蛋', '禽蛋', 15.8, 150),
            ('东北大米', '粮油', 45.8, 80),
            ('生抽', '调味品', 8.8, 200),
        ]
        
        for name, category_name, price, stock in products_data:
            category = Category.objects.get(name=category_name)
            Product.objects.get_or_create(
                name=name,
                defaults={
                    'category': category,
                    'price': price,
                    'stock': stock,
                    'description': f'优质{name}'
                }
            )
        
        self.stdout.write('商品创建完成')

    def create_orders(self):
        customer = User.objects.get(username='customer')
        products = Product.objects.all()
        
        # 创建5个订单
        for i in range(5):
            order = Order.objects.create(
                customer=customer,
                status=random.choice(['pending', 'completed', 'cancelled']),
                total_amount=0
            )
            
            # 每个订单添加2-4个商品
            total_amount = 0
            for _ in range(random.randint(2, 4)):
                product = random.choice(products)
                quantity = random.randint(1, 5)
                price = product.price
                
                OrderItem.objects.create(
                    order=order,
                    product=product,
                    quantity=quantity,
                    price=price
                )
                
                total_amount += price * quantity
            
            order.total_amount = total_amount
            order.save()
        
        self.stdout.write('订单创建完成')

    def create_deliveries(self):
        deliveryman = User.objects.get(username='deliveryman')
        orders = Order.objects.filter(status='completed')
        
        # 为已完成的订单创建配送任务
        for order in orders:
            Delivery.objects.get_or_create(
                order=order,
                defaults={
                    'deliveryman': deliveryman,
                    'status': random.choice(['pending', 'in_progress', 'completed']),
                    'delivery_time': timezone.now()
                }
            )
        
        self.stdout.write('配送任务创建完成') 

        # 添加销售订单测试数据
        self.stdout.write('开始生成销售订单测试数据...')
        # 这里需要根据实际的销售订单模型和数据库表结构编写插入语句
        # 示例：假设存在 SalesOrder 模型，有 customer, product, quantity, price 等字段
        # from your_app.models import SalesOrder
        # SalesOrder.objects.create(customer='test_customer', product='test_product', quantity=10, price=100)
        
        # 添加配送任务测试数据
        self.stdout.write('开始生成配送任务测试数据...')
        # 这里需要根据实际的配送任务模型和数据库表结构编写插入语句
        # 示例：假设存在 DeliveryTask 模型，有 order, delivery_person, status 等字段
        # from your_app.models import DeliveryTask
        # DeliveryTask.objects.create(order=SalesOrder.objects.first(), delivery_person='test_delivery_person', status='pending')